package com.project.basis.base;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.project.basis.receiver.ReceiverCallback;

import java.util.Objects;

public abstract class BaseActivity extends AppCompatActivity {

    /**
     * 广播
     */
    protected BaseBroadcastReceiver baseBroadcastReceiver;
    /**
     * 广播回调
     */
    protected ReceiverCallback baseReceiverCallback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); // 禁止横屏
        }
        setContentView(getContentViewId());
        initView(savedInstanceState);
        bindViewData(savedInstanceState);
        if (this instanceof ReceiverCallback) {
            baseReceiverCallback = (ReceiverCallback) this;
        }
    }

    protected abstract void initView(Bundle savedInstanceState);

    protected abstract void bindViewData(Bundle savedInstanceState);

    protected abstract int getContentViewId();

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = res.getConfiguration();
        config.fontScale = 1;
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }

    /**
     * 注册广播
     */
    protected void registerLoginBroadcast(String... actions) {
        baseBroadcastReceiver = new BaseBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        for (String action : actions) {
            intentFilter.addAction(action);
        }
        LocalBroadcastManager.getInstance(this).registerReceiver(baseBroadcastReceiver, intentFilter);
    }

    /**
     * 取消注册广播
     */
    protected void unRegisterLoginBroadcast() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(baseBroadcastReceiver);
    }

    protected class BaseBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (baseReceiverCallback != null && intent != null && !TextUtils.isEmpty(intent.getAction())) {
                baseReceiverCallback.onReceive(intent, intent.getAction());
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (baseBroadcastReceiver != null)
            unRegisterLoginBroadcast();
    }
}
